﻿using System.Collections.Generic;
using System.Dynamic;
using System.Linq;


namespace PleaseORM.Domain.Entity
{
	public abstract class DynamicEntity : DynamicObject
	{
		private IDictionary<string, dynamic> _proprieties;

		public DynamicEntity()
		{
			_proprieties = new Dictionary<string, dynamic> {{"Id", 0}};
		}

		public override bool TryGetMember(GetMemberBinder binder, out dynamic result)
		{
			result = _proprieties[binder.Name];
			return true;
		}

		public override bool TrySetMember(SetMemberBinder binder, dynamic value)
		{
			var columName = binder.Name;
			var columValue = value;

			SetValueMember(columName, columValue);

			return true;
		}

		public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
		{
			if (binder.Name.Equals("SetValueMember"))
			{
				SetValueMember(args[0].ToString(), args[1]);
				result = null;
				return true;
			}
			
			if (binder.Name.Equals("GetValue"))
			{
				GetValue(args[0].ToString(), out result);
				return true;
			}

			result = null;
			return false;
		}

		public override IEnumerable<string> GetDynamicMemberNames()
		{
			foreach(var prop in _proprieties)
			{
				yield return prop.Key;
			}
		}

		protected void GetValue(string member, out dynamic result)
		{
			result = _proprieties[member];
		}

		protected void SetValueMember(string columName, dynamic columValue)
		{
			if (_proprieties.ContainsKey(columName))
				_proprieties[columName] = columValue;
			else
				_proprieties.Add(columName, columValue);
		}
	}
}
